#include <tsin/SimpleMain.hpp>
#include <tsin/Argument.hpp>
#include <tsin/util/ConsoleLogger.hpp>
#include <tsin/util/GFXTimer.hpp>
#include <tsin/config/XMLConfig.hpp>
#include <tsin/selector/ConfigSelector.hpp>
#include <tsin/display/GLDisplay.hpp>
#include <tsin/display/GLImage.hpp>
#include <tsin/display/DecoratedImage.hpp>
#include <tsin/util/Resolution.hpp>
#include <tsin/library/TouhouSoloFront.hpp>
#include <tsin/runtime/GameRuntime.hpp>
#include <tsin/input/InputEvent.hpp>
#include <tsin/input/KeyboardInput.hpp>
#include <tsin/runtime/SpellEngine.hpp>
#include <tsin/library/TouhouPlayerFactory.hpp>
#include <tsin/util/Set.hpp>

#include <tsin/library/Game.hpp>

#include <cstring>

using namespace tsin;

static void setupLogger(Argument &arg)
{
        int loglvl = 4;
        arg.getOption('\0', "loglvl", loglvl);
        logp = new ConsoleLogger();
        logp->setFilterLevel(static_cast<Logger::LogLevel>(loglvl));

        tinfo << "Command line:";
        for (int i = 0; i < arg.size(); i ++)
                tcont << " " << arg.getArgument(i);
        tcont << "\n";
}

SimpleMain::SimpleMain()
{
}

int SimpleMain::main(Argument &arg)
{
        setupLogger(arg);

        XMLConfig config;

        /* Update the config according to cmdline */
        char buf[128];
        if (arg.getOption('f', "file", buf)) {
                int len = strlen(buf);
                delete config.file;
                config.file = new char[len + 1];
                memcpy(config.file, buf, len);
                config.file[len] = '\0';
        }

        GLDisplay display;
        display.setWindowIcon(RES_PREFIX "tsin_32.png");
        if (!display.init(config)) {
                talert << "Cannot init display.\n";
                return -1;
        }
        display.setWindowName("Touhou Shadow IllusioNs");

        GFXTimer timer(config);
        KeyboardInput input;

        GameRuntime runtime(config, display, input, timer);
        currentGame = &runtime;

        ConfigSelector selector(config);
        Game *game = selector.select();
        if (game == 0) {
                talert << "Cannot load game module.\n";
                return -1;
        }
        runtime.game = game;

        SpellEngine engine;
        engine.init(&runtime);
        engine.run(&runtime);

        return 0;
}

